package webserver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLConnection;

public class Servlet {
	private String documentRoot = "";

	public Servlet(String documentRoot) {
		this.documentRoot = documentRoot;
	}

	public boolean isMethodImplemented(String method) {
		return method.equals("GET") || method.equals("HEAD");
	}

	public Response service(Request request) throws IOException {
		Response resp = new Response(request.getMethod().equals("HEAD"));
		if (isMethodImplemented(request.getMethod())) {
			File source = new File(documentRoot
					+ request.getRequestURI().getRawPath());
			if (source.exists() && source.getCanonicalPath().startsWith(documentRoot)) {
				try {
					FileInputStream fis = new FileInputStream(source);
					byte[] contents = new byte[(int) source.length()]; // Won't
																		// read
																		// more
																		// than
																		// 3GB.
					int i = 0, c;
					try {
						while ((c = fis.read()) != -1) {
							contents[i++] = (byte) c;
						}

						String mimeType = URLConnection.getFileNameMap()
								.getContentTypeFor(source.getName());
						resp.setBytes(contents);
						resp.setCode("200");
						resp.setReason("OK");
						resp.setHeader("Content-Type",
								mimeType == null ? "text/plain" : mimeType);
					} catch (IOException e) {
						fis.close();
					}

				} catch (FileNotFoundException e) {
					resp.setCode("404");
					resp.setReason("File not found");
					resp.setBytes("<HTML>File not found</HTML>".getBytes());
				} catch (IOException e) {

				}
			} else {
				resp.setCode("404");
				resp.setReason("File not found");
				resp.setBytes("<HTML>File not found</HTML>".getBytes());
			}
		} else {
			resp.setCode("501");
			resp.setReason("Not Implemented");
			resp.setBytes("The requested method is not implemented.".getBytes());
		}

		return resp;
	}
}
